package com.ym.b2b.order.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ym.b2b.cache.configcache.WebAppConfig;
import com.ym.b2b.commons.exception.BaseException;
import com.ym.b2b.commons.service.BaseService;
import com.ym.b2b.order.DefaultTradeRequestImpl;
import com.ym.b2b.order.TradeRequest;
import com.ym.b2b.order.dao.EmSOrderAddressDao;
import com.ym.b2b.order.dao.EmSOrderConfirmItemDao;
import com.ym.b2b.order.dao.EmSOrderDao;
import com.ym.b2b.order.service.EmSOrderConfirmItemService;
import com.ym.b2b.order.sqlbean.EmSOrder;
import com.ym.b2b.order.sqlbean.EmSOrderAddress;
import com.ym.b2b.order.sqlbean.EmSOrderConfirmItem;
import com.ym.b2b.order.vo.OrderInfoVO;
import com.zc.commons.base.Page;
import com.zc.commons.base.Result;

@Service
public class EmSOrderConfirmItemServiceImpl extends BaseService implements EmSOrderConfirmItemService {

    @Autowired
    private EmSOrderConfirmItemDao emSOrderConfirmItemDao;

    @Autowired
    private EmSOrderDao            emSOrderDao;

    @Autowired
    private EmSOrderAddressDao     emSOrderAddressDao;

    @Autowired
    private TradeRequest           tradeRequest;

    @Override
    @Transactional
    public Result deleteEmSOrderConfirmItem(EmSOrderConfirmItem emSOrderConfirmItem,HttpServletRequest req) throws BaseException {
        EmSOrderConfirmItem emSOrderConfirmItem2 = emSOrderConfirmItemDao.searchEmSOrderConfirmItemDetail(emSOrderConfirmItem);
        Result result = new Result();
        result.setResult("删除成功");

        // 判断是否符合删除条件
        EmSOrder emSOrder = new EmSOrder();
        emSOrder.setOrderCode(emSOrderConfirmItem2.getOrderCode());
        emSOrder = emSOrderDao.searchOrderDetail(emSOrder);
        if (emSOrder.getStatus().doubleValue() > 1&& emSOrder.getStatus().doubleValue() !=10.0 || emSOrder.getStatus().doubleValue() == -1 ) {
            // 无法取消
            result.setCodeResult(Result.CODE_100, "当前订单状态为：" + emSOrder.getStrStatus() + ";无法删除!");
            return result;
        }

        try {
            if ("".equals(emSOrderConfirmItem.getOrderConfirmItemId())) {
                result.setCodeResult(Result.CODE_100, "删除条件有误!无法删除!");
                return result;
            }
//            logger.info("删除订单明细中.....................");
             emSOrderConfirmItemDao.deleteEmSOrderConfirmItem(emSOrderConfirmItem);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("删除订单明细失败!");
        }

        emSOrderConfirmItem.setOrderCode(emSOrder.getOrderCode());
        // 判断是否已经全部删除了
        Integer isDeleteAll = emSOrderConfirmItemDao.searchEmSOrderConfirmItemNum(emSOrderConfirmItem);
        OrderInfoVO vo=new OrderInfoVO();

        if (isDeleteAll > 0) {
            // 重新计算 订单金额
            EmSOrder emSOrder1 = new EmSOrder();
            emSOrder1.setOrderCode(emSOrder.getOrderCode());
            String isInvoice=req.getParameter("isInvoice");
            List<EmSOrderConfirmItem> orderConfigmItemList = emSOrderConfirmItemDao.searchEmSOrderConfirmItem(emSOrderConfirmItem);
            Double confirmMoney=0.0;
            for(EmSOrderConfirmItem item:orderConfigmItemList){
                confirmMoney+=item.getConfirmMoney();
            }
            String nowCase = WebAppConfig.getConfigMap().get("CURRENT_USE") == null ? "" : WebAppConfig.getConfigMap().get("CURRENT_USE").toString();
            if (!"".equals(nowCase)) {
                if (nowCase.equals("XC")) { // 宣城医药在线
                    emSOrder1.setTotalMoney(confirmMoney);// 总金额
                    emSOrder1.setConfirmMoney(confirmMoney);// 确认金额
                }else if(nowCase.equals("TK")){
                	BigDecimal bd = new BigDecimal(confirmMoney*1.09);
                    if(isInvoice!=null&&isInvoice=="1"){
                        confirmMoney=bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        emSOrder1.setTotalMoney(confirmMoney);// 总金额
                        emSOrder1.setConfirmMoney(confirmMoney);// 确认金额
                    }else{
                        emSOrder1.setTotalMoney(confirmMoney);// 总金额
                        emSOrder1.setConfirmMoney(confirmMoney);// 确认金额
                    }
                }
            }

            //emSOrder1.setOrderConfirmMoneySumitem("-----------");
            vo.setOrderCode(emSOrder.getOrderCode());
            vo.setConfirmMoney(confirmMoney);
            try {
                emSOrderDao.updateEmSOrder(emSOrder1);
                /* 在application_config.xml中控制判断什么时候对接ERP下订单 ,false 则在支付后下单, ture则在确认时下单  
                 * 对应到取消订单,表现为 true需要调用ERP接口, false不需要
                 */
                if (DefaultTradeRequestImpl.isBooking()) { 
                	vo.setErpCode(emSOrder.getOrderCodeErp());
                	vo.setBuyerCode(emSOrder.getBuyerCode());
                	tradeRequest.updateOrder(vo,orderConfigmItemList);
                }
                result.putData("money",confirmMoney);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new BaseException("更新总订单信息失败!");
            }
        } else {
            // delete em_s_order

            // 删除订单地址
            EmSOrderAddress emSOrderAddress = new EmSOrderAddress();
            emSOrderAddress.setOrderCode(emSOrder.getOrderCode());
            vo.setOrderCode(emSOrder.getOrderCode());
            vo.setErpCode(emSOrder.getOrderCodeErp());
            try {
                emSOrderAddressDao.deleteEmSOrderAddress(emSOrderAddress);
                emSOrderDao.deleteEmSOrder(emSOrder);
                /* 在application_config.xml中控制判断什么时候对接ERP下订单 , ture则在确认时下单,  false 则在支付后下单
                 * 对应到取消订单,表现为 true需要调用ERP接口, false不需要
                 */
                if (DefaultTradeRequestImpl.isBooking()) { 
                	tradeRequest.cancelOrder(vo);
                }
                result.setCodeResult("300","全部删除");
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new BaseException("删除订单失败");
            }
        }
        return result;
    }
    
    @Override
    public Result searchPageEmSOrderConfirmItem(EmSOrderConfirmItem emSOrderConfirmItem, Page<EmSOrderConfirmItem> page)
                                                                                                                        throws BaseException {
        Result ret = new Result();
        try {
            if (null == emSOrderConfirmItem.getGeStatus()) {
                emSOrderConfirmItem.setGeStatus(10);
            }

            emSOrderConfirmItemDao.searchPageEmSOrderConfirmItem(emSOrderConfirmItem, page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, e.getMessage());
        }
        ret.setResultPage(page);
        return ret;
    }

    @Override
    public Page<EmSOrderConfirmItem> searchPageEmSOrderConfirmItemReturn(EmSOrderConfirmItem emSOrderConfirmItem,
                                                                         Page<EmSOrderConfirmItem> page)
                                                                                                        throws BaseException {
        try {
            page = emSOrderConfirmItemDao.searchPageItemReturn(emSOrderConfirmItem, page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("列表查询异常");
        }
        return page;
    }

    @Override
    public Result updateConfirmItemForIsReturn(EmSOrderConfirmItem emSOrderConfirmItem) throws DataAccessException {
        Result result = new Result();
        try {
            emSOrderConfirmItemDao.updateConfirmItemForIsReturn(emSOrderConfirmItem);
            result.setResult("申请退货成功！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, e.getMessage());
        }
        return result;
    }

    @Override
    public Result updateMultipleConfirmItemForIsReturns(EmSOrderConfirmItem emSOrderConfirmItem)
                                                                                                throws DataAccessException {
        Result result = new Result();
        try {
            String p = emSOrderConfirmItem.getProductCodeList();
            String list = "'";
            if (!"".equals(p) && p != null) {
                String[] codes = p.split(",");
                for (int i = 0; i < codes.length; i++) {
                    if (i != codes.length - 1) {
                        list = list + codes[i] + "','";
                    } else {
                        list = list + codes[i] + "'";
                    }

                }
                emSOrderConfirmItem.setProductCodeList(list);
            }
            emSOrderConfirmItemDao.updateMultipleConfirmItemForIsReturns(emSOrderConfirmItem);
            result.setResult("批量申请退货成功！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, e.getMessage());
        }
        return result;
    }
}
